package com.android.WiFiQualityMeasurement;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.TextView;

/**
 *
 *
 */
public class WiFiQualityMeasurementActivity extends Activity implements OnTouchListener, LocationListener{
    /** Called when the activity is first created. */

	private LocationManager	mLocationManager;				// ロケーションマネージャ
	private Button 			mButtonLogOn;					// Log測定ON
	private Button 			mButtonLogOff;					// Log測定OFF

	private TextView		mTextViewLineType;				// 回線種別
	private TextView		mTextViewCareerName;			// キャリア名

	private TextView		mTextViewSsid;					// SSID
	private TextView		mTextViewBssid;					// B_SSID
	private TextView		mTextViewThroughput;			// スループット
	private TextView		mTextViewElectricFieldStrength;	// 電界強度

	private TextView		mTextViewTerminalMacAddress;	// 端末MACアドレス
	private TextView		mTextViewTerminalType;			// 端末種別

	private TextView		mTextViewLatitude;				// 緯度
	private TextView		mTextViewLongitude;				// 経度

	private TextView		mTextViewTime;					// 時刻

	private TextView		mTextViewPing;					// Ping結果

	private Button 			mButtonWifiOn;					// Wifi測定ON
	private Button 			mButtonWifiOff;					// Wifi測定OFF

	private boolean				mBooleanBroadcast = false;
	private boolean				mBlSendService = false;

	private IntentFilter		mIntentFilter;
	
	private Builder mAlertDialogBuilder;

	public class WiFiQualityMeasurementDrawInfoReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			// Intentレシーブしたときに呼ばれる
			Bundle bundle = intent.getExtras();

			mTextViewLineType.setText(bundle.getString("LINETYPE"));
			mTextViewCareerName.setText(bundle.getString("CAREERNAME"));
			mTextViewSsid.setText(bundle.getString("SSID"));
			mTextViewBssid.setText(bundle.getString("BSSID"));
			mTextViewThroughput.setText(bundle.getString("THROUGHPUT"));
			mTextViewElectricFieldStrength.setText(bundle.getString("ELECTRICFIELDSTRENGTH"));
			mTextViewTerminalMacAddress.setText(bundle.getString("MACADDRESS"));
			mTextViewTerminalType.setText(bundle.getString("MODEL"));
			mTextViewLatitude.setText(bundle.getString("LATITUDE"));
			mTextViewLongitude.setText(bundle.getString("LONGITUDE"));
			mTextViewTime.setText(bundle.getString("DAYTIME"));
			mTextViewPing.setText(bundle.getString("PINGRESULT"));

		}
	}

	private final WiFiQualityMeasurementDrawInfoReceiver mDrawReceiver = new WiFiQualityMeasurementDrawInfoReceiver();
	/* 2010.11.13 SANO ADD END */


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // View部品生成
        mButtonLogOn = (Button)findViewById(R.id.Button02);
        mButtonLogOff = (Button)findViewById(R.id.Button03);

        mTextViewLineType = (TextView)findViewById(R.id.TextView03);
        mTextViewLineType.setText("");
        mTextViewCareerName = (TextView)findViewById(R.id.TextView05);
        mTextViewCareerName.setText("");

        mTextViewSsid = (TextView)findViewById(R.id.TextView08);
        mTextViewSsid.setText("");
        mTextViewBssid = (TextView)findViewById(R.id.TextView10);
        mTextViewBssid.setText("");
        mTextViewThroughput = (TextView)findViewById(R.id.TextView12);
        mTextViewThroughput.setText("");
        mTextViewElectricFieldStrength = (TextView)findViewById(R.id.TextView14);
        mTextViewElectricFieldStrength.setText("");

        mTextViewTerminalMacAddress = (TextView)findViewById(R.id.TextView17);
        mTextViewTerminalMacAddress.setText("");
        mTextViewTerminalType = (TextView)findViewById(R.id.TextView19);
        mTextViewTerminalType.setText("");

        mTextViewLatitude = (TextView)findViewById(R.id.TextView22);
        mTextViewLatitude.setText("");
        mTextViewLongitude = (TextView)findViewById(R.id.TextView24);
        mTextViewLongitude.setText("");

        mTextViewTime = (TextView)findViewById(R.id.TextView27);
        mTextViewTime.setText("");

		mTextViewPing = (TextView)findViewById(R.id.TextView30);
		mTextViewPing.setText("");

        mButtonWifiOn = (Button)findViewById(R.id.Button04);
        mButtonWifiOff = (Button)findViewById(R.id.Button05);

        // ボタンへタッチイベント紐つけ
        mButtonLogOn.setOnTouchListener(this);
        mButtonLogOff.setOnTouchListener(this);
        mButtonWifiOn.setOnTouchListener(this);
        mButtonWifiOff.setOnTouchListener(this);

        mButtonLogOff.setEnabled(false);

		mLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);

		if(mLocationManager != null) {
			mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, // プロバイダ
													0, // 通知のための最小時間間隔
													0, // 通知のための最小距離間隔
													this); // 位置情報リスナー
		}

		mIntentFilter =	 new IntentFilter(WiFiQualityMeasurementDrawInfoService.ACTION);
		mBooleanBroadcast = false;
		
    	/* 2010.11.13 AOKI ADD START */
		mAlertDialogBuilder = new Builder(this);
		// タイトル
		mAlertDialogBuilder.setTitle(getString(R.string.gps_title));
		// 本文
		mAlertDialogBuilder.setMessage(getString(R.string.gps_question));
		// バックキーによるダイアログ非表示の無効化
		mAlertDialogBuilder.setCancelable(false);
		//GPS設定画面起動用ボタンとイベントの定義
		mAlertDialogBuilder.setPositiveButton(getString(R.string.gps_setting),
	              new DialogInterface.OnClickListener(){
	              public void onClick(DialogInterface dialog, int id){
	            	  // セキュリティ＆位置情報の設定画面へ遷移
	                  Intent callGPSSettingIntent = new Intent(
	                        android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
	                  startActivityForResult(callGPSSettingIntent, 0);
	              }
	         });
    	/* 2010.11.13 AOKI ADD END */
    }

	@Override
    protected void onResume() {
		if(mDrawReceiver != null)
		{
			registerReceiver(mDrawReceiver, mIntentFilter); // BroadcastReceiver登録
			mBooleanBroadcast = true;
		}

    	/* 2010.11.13 AOKI ADD START */
    	// GPSのチェック
    	isGPSService();

        // WiFiのチェックと開始
        isWiFiService();

        // WiFiレシーバーへ登録
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        registerReceiver(mWiFiStatusReceiver, filter);
    	/* 2010.11.13 AOKI ADD END */

    	super.onResume();
    }

    @Override
    protected void onPause() {
		if(mDrawReceiver != null && mBooleanBroadcast == true)
		{
			unregisterReceiver(mDrawReceiver); // BroadcastReceiver登録解除
			mBooleanBroadcast = false;
		}
    	/* 2010.11.13 AOKI ADD START */
    	unregisterReceiver(mWiFiStatusReceiver);
    	/* 2010.11.13 AOKI ADD END */

    	super.onPause();
    }

	@Override
	public void onDestroy() {
		if(mDrawReceiver != null && mBooleanBroadcast == true)
		{
			unregisterReceiver(mDrawReceiver); // BroadcastReceiver登録解除
			mBooleanBroadcast = false;
		}

		if( mBlSendService )
		{
			stopService(new Intent(WiFiQualityMeasurementActivity.this, WiFiQualityMeasurementSendInfoService.class));
			stopService(new Intent(WiFiQualityMeasurementActivity.this, WiFiQualityMeasurementDrawInfoService.class));
			mBlSendService = false;
		}
		super.onDestroy();
	}


	@Override
	public boolean onTouch(View view, MotionEvent motionevent) {
		// TODO 自動生成されたメソッド・スタブ
		if(motionevent.getAction() == MotionEvent.ACTION_DOWN)
		{
			if (view == mButtonLogOn)
			{
				mButtonLogOn.setEnabled(false);
				mButtonLogOff.setEnabled(true);
				if( !mBlSendService )
				{
					startService(new Intent(WiFiQualityMeasurementActivity.this, WiFiQualityMeasurementSendInfoService.class));
					startService(new Intent(WiFiQualityMeasurementActivity.this, WiFiQualityMeasurementDrawInfoService.class));
					mBlSendService = true;
				}
			}
			else if(view == mButtonLogOff)
			{
				mButtonLogOff.setEnabled(false);
				mButtonLogOn.setEnabled(true);
				if( mBlSendService )
				{
					stopService(new Intent(WiFiQualityMeasurementActivity.this, WiFiQualityMeasurementSendInfoService.class));
					stopService(new Intent(WiFiQualityMeasurementActivity.this, WiFiQualityMeasurementDrawInfoService.class));
					mBlSendService = false;
				}
			}
			else if(view == mButtonWifiOn)
			{
				mButtonWifiOn.setEnabled(false);
				mButtonWifiOff.setEnabled(true);

				WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
				if(wifiManager != null)
				{
					wifiManager.setWifiEnabled(true);
				}
			}
			else if(view == mButtonWifiOff)
			{
				mButtonWifiOff.setEnabled(false);
				mButtonWifiOn.setEnabled(true);

				WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
				if(wifiManager != null)
				{
					wifiManager.setWifiEnabled(false);
				}
			}
		}
		return false;	// trueにするとタッチイベントがここで終わってボタンの押下描画がされない
	}

	/* 2010.11.13 AOKI ADD START */
	/**
	 * 端末のGPS機能が有効になっているかをチェックする。
	 * 無効になっている場合、有効にするダイアログを表示する。
	 */
	private void isGPSService() {
		LocationManager  maneger = (LocationManager) getSystemService(LOCATION_SERVICE);
		
		// GPSの通信許可中か
		boolean bProviderEnabled = maneger.isProviderEnabled(LocationManager.GPS_PROVIDER);
		
		AlertDialog alert = mAlertDialogBuilder.create();
		if (maneger != null && !bProviderEnabled) {
			// 設定画面へ移動するかの問い合わせダイアログを表示
			alert.show();
		}
	}

	/**
	 *  端末のWiFi機能の有効か無効かをチェックする。
	 *  接続可能なWiFiがあれば接続させる。
	 *  setEnabledが真の場合、ボタン有効
	 */
    private void isWiFiService() {
    	WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);

    	if (wifiManager != null) {
    		// WiFiの状態を取得
    		int wifiState = wifiManager.getWifiState();
    		switch (wifiState) {
    		// WiFi無効
    		case WifiManager.WIFI_STATE_DISABLED:
    			// WiFiをONにする
    		    wifiManager.setWifiEnabled(true);
		    	mButtonWifiOn.setEnabled(true);
		    	mButtonWifiOff.setEnabled(false);
    		    break;
    		// WiFi有効
    		case WifiManager.WIFI_STATE_ENABLED:
        		mButtonWifiOn.setEnabled(false);
        		mButtonWifiOff.setEnabled(true);
		    	break;
    		case WifiManager.WIFI_STATE_DISABLING:
    		case WifiManager.WIFI_STATE_ENABLING:
        		mButtonWifiOn.setEnabled(false);
        		mButtonWifiOff.setEnabled(false);
   			break;
    		}
    	}
	}

    /**
     * WiFiの状態によってボタンの有効無効を制御するレシーバクラス
     */
    public class WiFiQualityWiFiStatusReceiver extends BroadcastReceiver {
		public void onReceive(Context context, Intent intent) {
			if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(intent.getAction())) {
				WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
				int status = wm.getWifiState();
				switch (status)  {
		    		case WifiManager.WIFI_STATE_DISABLING:
		    		case WifiManager.WIFI_STATE_ENABLING:
		        		mButtonWifiOn.setEnabled(false);
		        		mButtonWifiOff.setEnabled(false);
		        		break;

					case WifiManager.WIFI_STATE_ENABLED:
		        		mButtonWifiOn.setEnabled(false);
		        		mButtonWifiOff.setEnabled(true);
		        		break;

					case WifiManager.WIFI_STATE_DISABLED:
		        		mButtonWifiOn.setEnabled(true);
		        		mButtonWifiOff.setEnabled(false);
		        		break;
				}
			}
		}
    }
    private WiFiQualityWiFiStatusReceiver mWiFiStatusReceiver = new WiFiQualityWiFiStatusReceiver();
    /* 2010.11.13 AOKI ADD END */


	@Override
	public void onLocationChanged(Location location) {
	}

	@Override
	public void onProviderDisabled(String s) {
	}

	@Override
	public void onProviderEnabled(String s) {
		// 自分に遷移、マニフェストファイルにsingleTaskを設定。常にルートになる。
		Intent i = new Intent(this, WiFiQualityMeasurementActivity.class);
		startActivity(i);
	}
	@Override
	public void onStatusChanged(String s, int i, Bundle bundle) {
	}
	/* 2010.11.13 SANO ADD END */
}
